package com.etoak.filter;


import cn.hutool.json.JSONUtil;
import com.etoak.common.core.properties.ImageProperties;
import com.etoak.common.core.vo.ResultVO;
import com.etoak.common.jwt.JwtUtil;
import com.etoak.propertiles.IgnoreProperties;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class TokenFilter implements GlobalFilter {

    @Autowired
    IgnoreProperties ignoreProperties;
    @Autowired
    ImageProperties imageProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 放行/user/login /code/getCode /pics开头
        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getPath().value();
        if (ignoreProperties.getUris().contains(uri) || uri.startsWith(imageProperties.getMapping())) {
            return chain.filter(exchange);
        }

        // 验证请求头中有没有 AUTHORIZATION
        String jwtString = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isEmpty(jwtString)) {
            return noAuth(exchange.getResponse(), "请传入令牌!");
        }

        try{
            JwtUtil.parse(jwtString);
        } catch (ExpiredJwtException e) {
            return noAuth(exchange.getResponse(), "令牌已过期!");
        } catch (Exception e) {
            return noAuth(exchange.getResponse(), "令牌错误!");
        }

        return chain.filter(exchange);
    }

    private Mono<Void> noAuth(ServerHttpResponse response, String message) {
        response.getHeaders().set(HttpHeaders.CONTENT_TYPE, "application/json;charset=utf-8");
        ResultVO<Object> resultVo = ResultVO.failed(403, message);
        String jsonStr = JSONUtil.toJsonStr(resultVo);
        DataBuffer dataBuffer = response.bufferFactory().wrap(jsonStr.getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }
}
